<?php
/* 
 *批发订单
 */
class WholesaleAction extends TransAction {
    public function _filter(&$map) {
        $key = trim($_REQUEST['keywords']);
        if(!empty($key)) {
                //$where['Wholesale_detail.sale_title'] = array('like',"%".$key."%");//产品名称
                //$where['Customer.name'] = array('like',"%".$key."%");//产品名称
                $where['shipping_name'] = array('like',"%".$key."%"); 
                $where['logino'] = array('like',"%".$key."%");
                $where['address'] = array('like',"%".$key."%");
                $where['mobile'] = array('like',"%".$key."%");
                $where['phone'] = array('like',"%".$key."%");
            
            $where['_logic'] = "or";
            $map['_complex'] = $where;
        }
        if(!empty($_REQUEST['order_no'])) {
            $key2 = trim($_REQUEST['order_no']);
            $map['wholesale_no'] = array('like',"%".$key2."%");
        }

        if( $_REQUEST['order_status'] != '' )
          $map['order_status'] = $_REQUEST['order_status'];

        if( $_REQUEST['order_source_id'] != '' )
          $map['wholesale_source_id'] = $_REQUEST['order_source_id'];
        //time 
        $cond_time = array();
        if( $_REQUEST['start_time'] != '' )
          array_push($cond_time, array( 'egt' , strtotime($_REQUEST['start_time']) ) );
          //$cond_time = array( 'egt' , strtotime($_REQUEST['start_time']) );
        if( $_REQUEST['end_time'] != '' )
          array_push($cond_time, array( 'elt' , strtotime($_REQUEST['end_time']) ) );

        //选择了时间类型,并且时间不为空，则按时间进行搜索
        if( $_REQUEST['time_type'] != "" && 
          ($_REQUEST['end_time'] != '' ||  $_REQUEST['start_time'] != '' ) ){
            switch ($_REQUEST['time_type']) {
              case '1': //审核时间
                $map['check_time '] = $cond_time;
                break;
              case '2': //发货时间
                $map['shipping_time '] = $cond_time;
                break;
              case '3': //下单时间
                if (empty($_REQUEST['keywords'])) {
                    
                    if($_REQUEST['etype'] == 'detail' ){ //导出订单详情，需按saleView进行搜索
                      $map['Wholesale.create_time '] = $cond_time;
                    }else
                      $map['create_time '] = $cond_time;
                }else
                    $map['Wholesale.create_time '] = $cond_time;
                break;
              default:  //按下单时间查询
                $map['create_time '] = $cond_time;
                break;
            }
            
        }

    }

    public function index()
    {
      //pass parameters to export_order function
      $parameters = str_replace(__URL__.'?', '', __SELF__);
      $this->assign('parameters' ,$parameters);
     $this->assign('meta_title','批发订单');
      parent::index();
    }

   public function print_sale(){
       parent::edit('Wholesale','print_sale');   
    }

    public function update()
    {
        $id = $_POST['id'];
        if(!empty($_POST['customer_id']))
          $_POST['customer_name'] = getModelName( $_POST['customer_id'] ,'Customer');
        $name ="Wholesale";
        $model = D('Wholesale');
            $old = $model->where('id = '.$id)->find();
            //如果是发货，则检查库存，库存不足，不能发货
           if($old['order_status'] == 2 && $_POST['order_status'] ==3 ){
                    $this->check_stock($id); //检查库存
                    if(empty($_POST['logino']))
                      $this->error("请输入快递单号！");
                }

            if (false === $model->create ()) {
                $this->error ( $model->getError () );
            }
            // 更新数据
            $list=$model->save ();
            if (false !== $list) {
                $new = $model->where('id = '.$id)->find();
                $mod_field = getModelName ($id, $name,$field);

                //如果由待发货改为已发货，则更新库存
                if($old['order_status'] ==2  && $new['order_status'] ==3 ){
                  $this->update_sale_stock($new['id']);
                }
                       

                //如果未取到字段值 ，则返回对应的ID编号
                $msg = '修改 '.$name.': '.$mod_field.' (编号：'.$id.')';
                if('Action' != $name)
                    A('Action')->writeLog($msg,'修改',$name,$id,$old,$new);
                //成功提示
                $jumpUrl = $_REQUEST['jumpUrl'];
                if(empty($jumpUrl))
                    $jumpUrl = Cookie::get ( '_currentUrl_' );
                $this->assign ( 'jumpUrl', $jumpUrl );
                $this->success ('编辑成功!');
            } else {
                //错误提示
                $this->error ('编辑失败!');
            }

    }

      
 //TODO 如果订单中产品库存不足，则返回提示
  public function check_stock($sale_id){
    /* 暂时不控制 2013-06-21
      $sale_details = M('Sale_detail')->where('sale_id ='.$sale_id)->field('product_id,number')->findAll();
      foreach ($sale_details as $value) {
        if(getModelName($value['product_id'],'Product','is_virtual') == 1  )
          continue; //虚拟物品，跳过处理
        $stock = getStock($value['product_id']);
        if($value['number'] > $stock)
          $this->error(getModelName($value['product_id'],'Product' )." 库存不足！",false,10);
      } */
  }

   //根据sale_id　减去订单的库存
    public function update_sale_stock($sale_id='')
    {
       $sale =  M('Wholesale')->getById($sale_id);
       //如果订单状态不为已发货，则不处理库存
       if($order_status = $sale['order_status'] != 3 )
        return ;
      $detail_datas = M('Wholesale_detail')->where( 'wholesale_id = '. $sale_id)->findAll() ;
      $trans = A('Trans');
      foreach ($detail_datas as $detail_data) {
        if(getModelName($detail_data['product_id'],'Product','is_virtual' ) == 1 )
          continue; //虚拟物品不减库存
        $trans->updateStock($detail_data['product_id'], $detail_data['warehouse_id'], 'out', $detail_data['number'] );
      }
      
    }

    //TODO
    public function export_order($value='')
    {
       //替换查询的函数，可以得map.再导出结果
      //file type: order,order_detail,both
      $export_type = $_REQUEST['etype'];
      switch ($_REQUEST['action']) {
        case 'can_not_shipping':
          $map['order_status'] = 2;
          $map['logino'] = '';
          break;
        case 'toshipping':
          $map['order_status'] = 2;
          $map['logino'] = array('neq','');
          $map['logicompany_id'] = array('neq',0);
          break;

        default: //index
         
          break;
      }
      $this->_filter ( $map );
      $line = "";
      $data = array();
      $goods = S('goods');
      switch ($export_type) {
             case 'order':
             if(empty($_REQUEST['keywords']))
                $voList = D('Wholesale')->where($map)->group('id')->findAll( );
              else
                $voList = D('WholesaleView')->where($map)->group('wholesale_id')->findAll( );

               $title ="订单编号,客户,货款,运费,应付款,订单状态,收货人姓名,手机,联系电话,收货地址,下单时间,付款时间,发货时间,物流单号,物流公司,总数量,订单来源\n";
                $title = iconv('utf-8', 'GBK', $title);
                if( is_array($voList) )
                foreach ($voList as $key => $value) {
                  $data= array(
                     'wholesale_no' => $value['wholesale_no'],

                     'customer_name' => iconv('utf-8','GBK',$value['customer_name'] ),
                     'total' => getGoodsTotalMoney($value['wholesale_no'],'wholesale'),
                     'logifee' => $value['logifee'],
                      'should_pay' => $value['should_pay'],
                      
                      'order_status' => $value['order_status'] == 2 ? iconv('utf-8','GBK',"等待卖家发货") :
                              iconv('utf-8','GBK', getConfigVal($value['order_status'],'orderstatus') ),
                     
                      //收货信息
                      'shipping_name' => iconv('utf-8','GBK',$value['shipping_name']), 
                      'mobile' => iconv('utf-8','GBK',$value['mobile']),
                      'phone' => iconv('utf-8','GBK',$value['phone']),
                      'address' => iconv('utf-8','GBK',$value['address']), 
                      
                      'create_time' => toDate($value['create_time']),
                      'pay_time' => toDate($value['pay_time']),
                      'shipping_time' => toDate($value['shipping_time']),

                      'logino' => iconv('utf-8','GBK',$value['logino']),
                      'logicompany' => iconv('utf-8','GBK',getModelName( $value['logicompany_id'],'Logicompany' ) ), //中文转码 
                      
                      'sum_number' => $value['sum_number'],
                      'order_source' => iconv('utf-8','GBK',getConfigVal( $value['wholesale_source_id'] , 'wholesale_source') ),
                     );
                    $line .= build_csv_line($data);
                    unset($data);
                } 
                $filename = "DYW_pforder".date('Ymd_His').'.csv'; //设置文件名 
                
                export_csv($filename,$title.$line);
               break;
            case 'detail':
               $voList = D('WholesaleView')->where($map)->findAll( );
               $title ="订单编号,客户,商品名称,商品编号,单价,数量,小计\n";
                $title = iconv('utf-8', 'GBK', $title);
                $data = array();
                 if( is_array($voList) )
                foreach ($voList as $key => $value) {
                  $data= array(
                     'sale_no' => $value['wholesale_no'],
                     'customer_name' => iconv('utf-8', 'GBK',$value['customer_name'] ),
                     'pname' => iconv('utf-8', 'GBK',$goods[$value['product_id'] ]['name'] ),
                     'product_id' => $value['product_id'],
                     'price' => $value['price'],
                     'number' => $value['number'],
                     'total' => $value['dtotal']
                     );
                   $line .= build_csv_line($data);
                    unset($data);
                }
                $filename = "DYW_pfgoods".date('Ymd_His').'.csv'; //设置文件名 
                
                export_csv($filename,$title.$line);

               break;
             case 'both':

             default:
               if(empty($_REQUEST['keywords']))
                $voList = D('Wholesale')->where($map)->group('id')->findAll( );
              else
                $voList = D('WholesaleView')->where($map)->group('sale_id')->findAll( );

               $title ="订单编号,会员名,货款,运费,应付款,订单状态,收货人姓名,手机,联系电话,收货地址,下单时间,付款时间,物流单号,物流公司,订单备注,总数量,订单来源\n";
                $title = iconv('utf-8', 'GBK', $title);
                 if( is_array($voList) )
                foreach ($voList as $key => $value) {
                  $data= array(
                     'sale_no' => $value['wholesale_no'],
                     'customer_name' => iconv('utf-8','GBK',$value['customer_name'] ),
                     'total' => getGoodsTotalMoney($value['wholesale_no']),
                     'logifee' => $value['logifee'],
                      'should_pay' => $value['should_pay'],
                      
                      'order_status' => $value['order_status'] == 2 ? iconv('utf-8','GBK',"等待卖家发货") :
                              iconv('utf-8','GBK', getConfigVal($value['order_status'],'orderstatus') ),
                     
                      //收货信息
                      'shipping_name' => iconv('utf-8','GBK',$value['shipping_name']), 
                      'mobile' => iconv('utf-8','GBK',$value['mobile']),
                      'phone' => iconv('utf-8','GBK',$value['phone']),
                      'address' => iconv('utf-8','GBK',$value['address']), 
                      

                      'create_time' => toDate($value['create_time']),
                      'pay_time' => toDate($value['pay_time']),

                      'logino' => $value['logino'],
                      'logicompany' => iconv('utf-8','GBK',getModelName( $value['logicompany_id'],'Logicompany' ) ), //中文转码 
                      
                      'sum_number' => $value['sum_number'],
                      'order_source' => iconv('utf-8','GBK',getConfigVal( $value['wholesale_source_id'] , 'wholesale_source') ),
                     );
                  $line .= build_csv_line($data);
                    unset($data);
                    $goods = M('Wholesale_detail')->where('wholesale_no ="'.$value['wholesale_no'].'"')->findAll();
                    foreach ($goods as  $v) {
                      $goods_data= array(
                       'blank' => "",
                       'pname' => iconv('utf-8', 'GBK',$goods[$v['product_id']]['name'] ),
                       
                       'product_id' => $v['product_id'],
                       'price' => $v['price'],
                       'number' => $v['number'],
                       'total' => $v['total']
                     );
                      $line .= build_csv_line($goods_data);
                    }
                    
                }

                $filename = "DYW_OrderGoods".date('Ymd_His').'.csv'; //设置文件名 
                export_csv($filename,$title.$line);
               break;
           }     
    }

     //import enter product detail
    public function import(){
        $sheetData = A('Import')->getExcel();
        $Product = M('Product');
        $product_str = "";
        $i = 1; //count import record
        foreach ($sheetData as $key => $value) {
            if ($key > 1) {//从第二行开始读取
                if(empty($value['A']) && empty ($value['B']) )
                   continue;
               $data = array(
                   'tm' => trim($value['A']),   //条码
                   'name' => trim($value['B']),   //数量
                   'number' => trim($value['C']),   //数量
                   'price' => trim($value['D']),   //进价
               );
               //不使用对象$Product->name 以免继承使用之前的值
                    //优先取条码名，如果条码为空，则取第二列的产品名称
                $pt =  empty($data['tm']) ? $Product->getByName($data['name']) : $Product->getByTm($data['tm']) ;
                if(empty($pt) )
                  $pt = $Product->getByName($data['name']);

                $name = $pt['name']; 
                if (empty($name)) {
                   //异常记录显示出来，人工去重后再进行插入操作
                  $data['name'] = '<font color="red">EXCEL第  '.$key.'  行异常,请删除</font>';
                }else{
                    $data['name'] = $name;
                }
                //json only filter td,not li ,so use li to stand out
            $data['unit'] = getModelName($Product->unit_id, 'Unit');
            $product_str .= "<tr class='tLeft' id='product_td'>";
            $product_str .="<td>" . $pt['tm'] . '</td>';
            $product_str .="<td><input type='hidden' name='product_id[]' value='" . $Product->id. "'/> <p class='span3'>" . $data['name'] . '</p></td>';
            $product_str .="<td>" . printLensOption($Product->id) . '</td>';
            $product_str .="<td>批价：".$Product->wholesale_price_default."</td>"; 
            $product_str .="<td><input type='text' class='input-mini' name='price[]' value='" . $data['price'] . "'/></td>";
            $product_str .="<td><input type='text' class='input-mini' name='number[]' class ='small' value='".$data['number']."' /></td>";    //数量
            $product_str .="<td class='span1'>" . $data['unit'] . "</td>";    //单位
            $product_str .="<td class='span1'>" . getStock($Product->id,1) . "</td>";    //库存,暂时默认青云路仓库TODO
            $product_str .="<td><input type='text' class='input-small' name='lot[]' value='' /></td>";   //产品批号
            $product_str .="<td><input type='text' class='input-small' name='exp[]' onClick='WdatePicker()' value='' /></td>";   //有效期
            
           $product_str .=  " <td class='span1'><img src='".__APP__."/Public/images/publish_x.png' alt='删除' onclick='removerow(this);'/>".$i."</td></tr>";
            $data = NULL;
            $i++;
            }
        }
        echo "{";
        echo                "error: '" . $error . "',\n";
        echo                "msg: '" . urlencode(($product_str)) . "'";
        echo "}";
       
    }

    
}
?>
